//
//  LHDownView.m
//  下拉菜单
//
//  Created by lehuo on 2017/1/13.
//  Copyright © 2017年 lehuo. All rights reserved.
//

#import "LHDownView.h"
#import "LHDownCell.h"
#define kScreenW [UIScreen mainScreen].bounds.size.width
#define kScreenH [UIScreen mainScreen].bounds.size.height
#define ArrowWidth 12//尖角的宽
#define ArrowHeight 10//尖角的高
#define RectRadius 10//圆角矩形的弧度
#define ContentSpace 12//tableview的左  右间距
#define ContentWidth 115//没有图标的tableView的宽度
#define IconWidth 135//有图标的tableView的宽度
#define TableViewCellHeight 40//cell的高度
#define MaxTableViewHeight  200//tableview的最大高度

typedef enum
{
    IconType,//有图标
    ConntentType//无图标
}LHDownViewType;

@interface LHDownView()<UITableViewDataSource,UITableViewDelegate>
@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,assign)CGRect frames;//传来view的绝对位置
@property(nonatomic,strong)NSArray <NSString *>*titleArray;//标题数组
@property(nonatomic,strong)SelectIndex selectIndex;//回调Block
@property(nonatomic,strong)NSArray *imgArray;//图片数组
@property(nonatomic,assign)LHDownViewType downType;//下拉菜单类型
@end
static NSString *iconCell = @"iconcell";//有图标
static NSString *contentCell = @"cell";//没有图标
@implementation LHDownView

#pragma mark - 弹出下拉菜单(没有图标)
+ (void)shownDownViewWithView:(UIView *)fromView optionTitle:(NSArray *)titleArray Block:(SelectIndex)selectIndex
{
    UIWindow *window  = [[UIApplication sharedApplication].delegate window];
    CGRect frame = [fromView convertRect:fromView.bounds toView:window];
    LHDownView *downView = [[LHDownView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    downView.backgroundColor = [UIColor clearColor];
    downView.frames = frame;
    downView.titleArray = titleArray;
    downView.selectIndex = selectIndex;
    downView.downType = ConntentType;
    [[UIApplication sharedApplication].keyWindow addSubview:downView];
    [downView showDownView];
    
}

#pragma mark - 弹出下拉菜单(没有图标)
+ (void)shownDownViewWithView:(UIView *)fromView optionTitle:(NSArray *)titleArray images:(NSArray *)imgArray Block:(SelectIndex)selectIndex
{
    UIWindow *window  = [[UIApplication sharedApplication].delegate window];
    CGRect frame = [fromView convertRect:fromView.bounds toView:window];
    LHDownView *downView = [[LHDownView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    downView.backgroundColor = [UIColor clearColor];
    downView.frames = frame;
    downView.titleArray = titleArray;
    downView.selectIndex = selectIndex;
    downView.imgArray = imgArray;
    downView.downType = IconType;
    [[UIApplication sharedApplication].keyWindow addSubview:downView];
    [downView showDownView];
}


#pragma mark - 懒加载 tableView
- (UITableView *)tableView
{
    if (!_tableView)
    {
        _tableView = [[UITableView alloc] init];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.backgroundColor =  [UIColor colorWithRed:110.0 / 255.0 green:110.0 / 255.0 blue:110.0 / 255.0 alpha:0.0];
        if(self.downType == IconType)
            _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:contentCell];
        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([LHDownCell class]) bundle:nil] forCellReuseIdentifier:iconCell];
        [self addSubview:_tableView];
    }
    return _tableView;
}

#pragma mark - 计算思路
/**
 *@brief 计算弹出框的位置
 *思路：通过传过来的view向对于屏幕的位置，来判断弹窗显示在view的上方还是下方，如果上方比较高就显示在上方，反之亦然。弹窗小箭头的x坐标位于view的中间x坐标紧贴view的上方或者下方，并且弹窗的上下左右都距离屏幕10
 */

#pragma mark - 计算弹出框的位置
- (void)showDownView
{
    CGFloat width = self.downType == IconType ? IconWidth :ContentWidth;
    //弹出框的宽和高
    CGFloat rectW = width + ContentSpace;
    CGFloat tableViewH;
    if(TableViewCellHeight * self.titleArray.count > MaxTableViewHeight)
        tableViewH = MaxTableViewHeight;
    else
        tableViewH = TableViewCellHeight * self.titleArray.count;
        
    CGFloat rectH = tableViewH + 20;
    
    CGFloat centerX = self.frames.origin.x + self.frames.size.width * 0.5;
    CGFloat centerY = self.frames.origin.y + self.frames.size.height * 0.5;
    CGPoint center = CGPointMake(centerX, centerY);
    CGFloat rectTL = center.x - rectW * 0.5;
    CGFloat rectTR = center.x + rectW * 0.5;
    CGFloat originY = 0;
    BOOL atUP = (self.frames.origin.y - 20) > (kScreenH - CGRectGetMaxY (self.frames) - 20);
    if(atUP)
    {
        if (self.frames.origin.y - 20 < rectH)
        {
            rectH = self.frames.origin.y - 20;
            originY = self.frames.origin.y - ArrowHeight;
            
        }else
        {
            originY = self.frames.origin.y - ArrowHeight;
        }
    }else
    {
        if (kScreenH - 20 - CGRectGetMaxY(self.frames) < rectH)
        {
            originY = CGRectGetMaxY(self.frames) + ArrowHeight;
            rectH = kScreenH  - CGRectGetMaxY(self.frames) - 20;
        }else
        {
            originY = CGRectGetMaxY(self.frames) + ArrowHeight;
            
        }
    }
    
    
    if (rectTL < 5)
    {
        rectTL = 5;
        rectTR = rectTL + rectW;
    }
    if (rectTR > kScreenW)
    {
        rectTR = kScreenW - 5;
        rectTL = rectTR - rectW;
    }
    CGRect rect;
    if(atUP) rect = CGRectMake(rectTL, originY - rectH, rectW, rectH);
    else rect = CGRectMake(rectTL, originY, rectW, rectH);
    
  
    
    NSArray *pointArray = [self calcultePoints:self.frames atUp:atUP];
    CGPoint centerPoint = CGPointFromString(pointArray[0]);
    CGPoint leftPoint = CGPointFromString(pointArray[1]);
    CGPoint rightPoint = CGPointFromString(pointArray[2]);

 
    UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:rect byRoundingCorners:UIRectCornerAllCorners cornerRadii:CGSizeMake(5, 5)];
    CAShapeLayer *layer = [CAShapeLayer layer];
    layer.path = path.CGPath;
    layer.fillColor =  [UIColor colorWithRed:30/255.0 green:30/255.0 blue:30/255.0 alpha:0.8].CGColor;
    [self.layer addSublayer:layer];

    UIBezierPath *otherPath = [UIBezierPath bezierPath];
    [otherPath moveToPoint:centerPoint];
    [otherPath addLineToPoint:leftPoint];
    [otherPath addLineToPoint:rightPoint];
    [otherPath addLineToPoint:centerPoint];
    CAShapeLayer *arrowLayer = [CAShapeLayer layer];
    arrowLayer.path = otherPath.CGPath;
     arrowLayer.fillColor =  [UIColor colorWithRed:30/255.0 green:30/255.0 blue:30/255.0 alpha:0.8].CGColor;
    [self.layer addSublayer:arrowLayer];

    /*******************确定tableView的frame***********************/
    if(!atUP)
        self.tableView.frame = CGRectMake(rectTL + ContentSpace * 0.5, originY  + ContentSpace * 0.5, rectW - ContentSpace, rectH - ContentSpace);
    else
        self.tableView.frame = CGRectMake(rectTL + ContentSpace * 0.5, self.frames.origin.y - rectH - ContentSpace * 0.5, rectW - ContentSpace, rectH - ContentSpace);
}


#pragma mark - 计算出弹窗小箭头三个点的位置
- (NSArray *)calcultePoints:(CGRect)frame atUp:(BOOL)atUP
{
    NSArray * result;
    CGFloat centerX = frame.origin.x + frame.size.width * 0.5;
    CGFloat centerY = frame.origin.y + frame.size.height * 0.5;
    CGPoint centerPoint = CGPointMake(centerX, centerY);
    if(atUP)
    {
       
        CGFloat originY = frame.origin.y;
        CGFloat originX = centerPoint.x;
        CGPoint originPoint = CGPointMake(originX, originY);
        CGPoint leftPoint = CGPointMake(originX - ArrowWidth * 0.5, originY - ArrowHeight);
        CGPoint rightPoint = CGPointMake(originX + ArrowWidth * 0.5, originY - ArrowHeight);
        result = @[NSStringFromCGPoint(originPoint),NSStringFromCGPoint(leftPoint),NSStringFromCGPoint(rightPoint)];
        
        
    }else
    {
        CGFloat originY = CGRectGetMaxY(frame);
        CGFloat originX = centerPoint.x;
        CGPoint originPoint = CGPointMake(originX, originY);
        CGPoint leftPoint = CGPointMake(originX - ArrowWidth * 0.5, originY + ArrowHeight);
        CGPoint rightPoint = CGPointMake(originX + ArrowWidth * 0.5, originY + ArrowHeight);
        result = @[NSStringFromCGPoint(originPoint),NSStringFromCGPoint(leftPoint),NSStringFromCGPoint(rightPoint)];
    }
    return result;
}

#pragma mark - UITableView代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.titleArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.downType == IconType) {
        LHDownCell *cell = [tableView dequeueReusableCellWithIdentifier:iconCell];
        cell.textLabel.textColor = [UIColor whiteColor];
        cell.contentLabel.text = self.titleArray[indexPath.row];
        id img = self.imgArray[indexPath.row];
        if ([img isKindOfClass:[NSString class]])
            cell.iconView.image = [UIImage imageNamed:img];
        else
            cell.iconView.image = img;
        cell.backgroundColor = [UIColor clearColor];
        return cell;

    }else
    {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:contentCell];
        cell.textLabel.textColor = [UIColor whiteColor];
        cell.textLabel.text = self.titleArray[indexPath.row];
        cell.backgroundColor = [UIColor clearColor];
        return cell;
    }
    }

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"%zd",indexPath.row);
    self.selectIndex(indexPath.row);
    [self removeFromSuperview];

}

#pragma mark - 点击UITableView范围外移除视图
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint point = [touch locationInView:self];
    point = [self.tableView.layer convertPoint:point fromLayer:self.layer];
    if (![self.tableView.layer containsPoint:point]) {
        [self removeFromSuperview];
    }
    
}
@end
